﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;

namespace Qadir.Data
{
    /// <summary>
    /// A class representing an object-relational model on a database.
    /// </summary>
    public static partial class ORM
    {
        public class RowController : QadirObject<DataRow>
        {
            public RowController(DataRow row)
                :base(row)
            {

            }

            /// <summary>
            /// Creates a new U with properties and fields copied from the row's columns.
            /// </summary>
            /// <typeparam name="U">The type of object to create.</typeparam>
            /// <param name="caseSensitive">A boolean value determining if property and field searching should be case-sensitive.</param>
            /// <returns>Returns a new U with compatible properties copied to each other.</returns>
            public override U LooseConvert<U>(bool caseSensitive = true)
            {
                U result = (U)Activator.CreateInstance<U>();

                FieldInfo[] uFields = typeof(U).GetFields();
                PropertyInfo[] uProperties = typeof(U).GetProperties();

                foreach (DataColumn column in BaseObject.Table.Columns)
                {
                    foreach (FieldInfo field in uFields)
                    {
                        if (string.Compare(field.Name, column.ColumnName, !caseSensitive) == 0)
                        {
                            if (field.FieldType == BaseObject[column].GetType())
                                field.SetValue(result, BaseObject[column]);
                        }
                    }

                    foreach (PropertyInfo property in uProperties)
                    {
                        if (string.Compare(property.Name, column.ColumnName, !caseSensitive) == 0)
                        {
                            if (property.PropertyType == BaseObject[column].GetType())
                                SetProperty(property.Name, BaseObject[column]);
                        }
                    }
                }
                return result;
            }
        }
    }
}
